package com.example.zx.theline.sgjh;

import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;

import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;

import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.example.zx.theline.BodyActivity;
import com.example.zx.theline.R;
import com.example.zx.theline.sgjh.pub.EditorGuardianActivity;
import com.loopj.android.http.RequestParams;
import com.scu.miomin.shswiperefresh.core.SHSwipeRefreshLayout;
import com.scu.miomin.shswiperefresh.view.SHListView;

import org.apache.http.Header;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import GsonBean.AddPointBean;
import GsonBean.CheckInfoBean;
import GsonBean.CheckPlanBean;
import Utils.BackHandlerHelper;
import Utils.DateUtil;
import app.MyApplication;
import base.BaseFragment;
import bean.CheckSearchBean;

import dialog.AddDangerPointDialog;
import dialog.ZsrjhChaKanDialog;
import network.NetWorkApi;
import network.ObjectHttpResponseHandler;
import Utils.MyToast;
import Utils.NoDoubleClickUtils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import views.CheckSearchView;

/**
 * Created by zx on 2017/4/27.
 */

public class CheckListCxFragment extends BaseFragment {

    private SHSwipeRefreshLayout swipeRefreshLayout;
    private SHListView mListView;
    private TextView mFootTextView;

    ZsrjhChaKanDialog mZsrjhChaKanDialog;
    CheckListAdapter mCheckListAdapter;

    //填充listview的数据
    List<CheckPlanBean.RowsBean> mSoureList;
    //分页数据 正常信息
    int pageNumber = 0;
    int pageSize = 10;

    CheckPlanBean mCheckPlanBean;

    //未超时计划：0 已超时计划：1 施工监护人员查询：2
    String isTimeOut = "0";
    private Intent intent;

    private TextView leftTextView, prev, centerTextView, next, rightTextView;

    CheckSearchView mCheckSearchView;
    CheckSearchBean mCheckSearchBean;
    //标记fragment onstart时是否需要刷新
    public static boolean onStartRefresh = false;

    //增加风险点dialog
    AddDangerPointDialog mAddDangerPointDialog;

    @Override
    protected void onFragmentFirstVisible() {
        super.onFragmentFirstVisible();
        InitData();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_normal, container, false);

        mListView = (SHListView) view.findViewById(R.id.listview_normal);
        //swipeRefreshLayout 下拉是刷新 上滑加载layout
        swipeRefreshLayout = (SHSwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);
        //swipeRefreshLayout footview
        View FootView = inflater.inflate(R.layout.refresh_view, null);
        mFootTextView = (TextView) FootView.findViewById(R.id.title);
        swipeRefreshLayout.setFooterView(FootView);

        leftTextView = (TextView) view.findViewById(R.id.leftTextView);
        rightTextView = (TextView) view.findViewById(R.id.rightTextView);
        centerTextView = (TextView) view.findViewById(R.id.centerTextView);
        prev = (TextView) view.findViewById(R.id.prev);
        next = (TextView) view.findViewById(R.id.next);
        mCheckSearchView = (CheckSearchView) view.findViewById(R.id.checksearchview);
        //隐藏是否超时选项
        mCheckSearchView.hideSfcs();
        InitListen();
        InitSearchView();
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (onStartRefresh) {
            RefreshAllDate(1, 10);
            onStartRefresh = false;
        }
    }


    protected void InitData() {
        mSoureList = new ArrayList<>();
        mCheckListAdapter = new CheckListAdapter();
        mListView.setAdapter(mCheckListAdapter);

        centerTextView.setText(DateUtil.getYearAndMonthAndDay(date));
        mCheckSearchBean = new CheckSearchBean();
        //初始化搜索条件，搜索日期为当天
        mCheckSearchBean.setSgrq(DateUtil.getYearAndMonthAndDay(date));
        LoadMoreDate();
    }

    public void InitSearchView() {

        prev.setText("上一日");
        next.setText("下一日");
        centerTextView.setText(DateUtil.getYearAndMonthAndDay(date));
        mCheckSearchView.setConfirmListener(new CheckSearchView.OnClick() {
            @Override
            public void onConfirmListener(CheckSearchBean Util) {
                mCheckSearchBean = Util;
                swipeRefreshLayout.startRefresh();
                RefreshAllDate(1, 10);
            }
        });
    }

    @Override
    public boolean onBackPressed() {
        if (mCheckSearchView.getVisibility() == View.VISIBLE) {
            mCheckSearchView.setVisibility(View.GONE);
            return true;
        } else {
            return BackHandlerHelper.handleBackPress(this);
        }
    }

    protected void InitListen() {
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                butNext();
            }
        });
        prev.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                butPrev();
            }
        });

        rightTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (mCheckSearchView.getVisibility() == View.GONE) {
                    mCheckSearchView.setVisibility(View.VISIBLE);
                    mCheckSearchView.setDefaultDate(mCheckSearchBean);
                }

            }
        });
        centerTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                TimePickerView.getInstance(getContext(), CheckListCxFragment.this.date, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        CheckListCxFragment.this.date = date;
                        setSearchBean();
                        upDatedAndRefresh();
                        RefreshAllDate(1, 10);
                    }
                }).show();

            }
        });

        leftTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BodyActivity.startThis(getActivity());
            }
        });


        swipeRefreshLayout.setOnRefreshListener(new SHSwipeRefreshLayout.SHSOnRefreshListener() {

            //下滑刷新 完成
            @Override
            public void onRefresh() {
                //下滑更新ListView内所有数据 包括高级查询在内   后三个参数分别为查询条件：施工日期 日计划号 相关单位编号
                RefreshAllDate(1, 10);

            }

            //上拉加载 完成
            @Override
            public void onLoading() {
                //加载更多数据
                LoadMoreDate();

            }

            /**
             * 监听下拉刷新过程中的状态改变
             * @param percent 当前下拉距离的百分比（0-1）
             * @param state 分三种状态{NOT_OVER_TRIGGER_POINT：还未到触发下拉刷新的距离；OVER_TRIGGER_POINT：已经到触发下拉刷新的距离；START：正在下拉刷新}
             */

            //下滑 刷新数据
            @Override
            public void onRefreshPulStateChange(float percent, int state) {
                switch (state) {
                    case SHSwipeRefreshLayout.NOT_OVER_TRIGGER_POINT:
                        swipeRefreshLayout.setRefreshViewText("下拉刷新");

                        break;
                    case SHSwipeRefreshLayout.OVER_TRIGGER_POINT:
                        swipeRefreshLayout.setRefreshViewText("松开刷新");

                        break;
                    case SHSwipeRefreshLayout.START:
                        swipeRefreshLayout.setRefreshViewText("正在刷新");

                        break;
                }
            }

            //上拉 加载更多数据
            @Override
            public void onLoadmorePullStateChange(float percent, int state) {
                switch (state) {
                    case SHSwipeRefreshLayout.NOT_OVER_TRIGGER_POINT:
                        mFootTextView.setText("上拉加载");
                        break;
                    case SHSwipeRefreshLayout.OVER_TRIGGER_POINT:
                        mFootTextView.setText("松开加载");
                        break;
                    case SHSwipeRefreshLayout.START:
                        mFootTextView.setText("正在加载...");
                        break;
                }
            }
        });
    }

    //设置搜索日期
    private void setSearchBean() {
        mCheckSearchBean.setSgrq(DateUtil.getYearAndMonthAndDay(date));
    }

    //按钮上一天事件
    public void butPrev() {
        date = DateUtil.getAfterDayDate(date, -1);
        setSearchBean();
        upDatedAndRefresh();
    }

    //按钮下一天事件
    public void butNext() {
        date = DateUtil.getAfterDayDate(date, 1);
        setSearchBean();
        upDatedAndRefresh();
    }

    //更新标题栏日期并刷新列表数据
    public void upDatedAndRefresh() {
        centerTextView.setText(DateUtil.getYearAndMonthAndDay(date));
        //刷新列表数据
        onRefresh();
    }


    public void onRefresh() {
        RefreshAllDate(1, 10);
    }

    public class CheckListAdapter extends BaseAdapter {


        @Override
        public int getCount() {

            return mSoureList.size();

        }

        @Override
        public Object getItem(int position) {


            return mSoureList.get(position);

        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            final ViewHolder mHolder;
            if (convertView == null) {
                convertView = LayoutInflater.from(getActivity()).inflate(R.layout.checklist_adapter, null);
                mHolder = new ViewHolder();
                mHolder.jihuahao = (TextView) convertView.findViewById(R.id.jihuahao);
                mHolder.shigongriqi = (TextView) convertView.findViewById(R.id.shigongriqi);
                mHolder.shigongleixing = (TextView) convertView.findViewById(R.id.shigongleixing);
                mHolder.shigongdidian = (TextView) convertView.findViewById(R.id.shigongdidian);
                mHolder.shigongxiangmu = (TextView) convertView.findViewById(R.id.shigongxiangmu);
                mHolder.jianhurenyuan = (TextView) convertView.findViewById(R.id.jianhurenyuan);
                mHolder.bjjhr = (TextView) convertView.findViewById(R.id.bjjhr);
                mHolder.bcfxd = (TextView) convertView.findViewById(R.id.bcfxd);
                mHolder.editlayout = (LinearLayout) convertView.findViewById(R.id.editlayout);
                convertView.setTag(mHolder);
            } else {
                mHolder = (ViewHolder) convertView.getTag();
            }
            mHolder.jihuahao.setText("" + mSoureList.get(position).getBh() + "");
            mHolder.shigongriqi.setText("" + mSoureList.get(position).getExsgrq() + "");
            mHolder.shigongleixing.setText(mSoureList.get(position).getLb() + "类");
            if (mSoureList.get(position).getLb().equals("B")) {
                mHolder.shigongleixing.setTextColor(getResources().getColor(R.color.colorTextB));
            } else if (mSoureList.get(position).getLb().equals("C")) {
                mHolder.shigongleixing.setTextColor(getResources().getColor(R.color.colorTextC));
            }
            mHolder.shigongdidian.setText("" + mSoureList.get(position).getSgdd() + "");
            mHolder.shigongxiangmu.setText("" + mSoureList.get(position).getXmmc() + "");
            mHolder.jianhurenyuan.setText("" + mSoureList.get(position).getJcjhr() + "");
            mHolder.bjjhr = (TextView) convertView.findViewById(R.id.bjjhr);
            mHolder.bcfxd = (TextView) convertView.findViewById(R.id.bcfxd);
            mHolder.editlayout = (LinearLayout) convertView.findViewById(R.id.editlayout);
            mHolder.linearlayout = (LinearLayout) convertView.findViewById(R.id.linearlayout);
            mHolder.linearlayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!NoDoubleClickUtils.isDoubleClick())
                        getCheckInfoData(mSoureList.get(position).getBh());
                }
            });

            if (mSoureList.get(position).getLrzt().equals("1")) {
                mHolder.bjjhr.setText("编辑监护人");
                mHolder.bcfxd.setText("补充风险点");

            } else {
                mHolder.bjjhr.setText("查看监护人");
                mHolder.bcfxd.setText("查看风险点");
            }
            //指派监护人的按钮
            mHolder.bjjhr.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    EditorGuardianActivity.jdjhbBh = mHolder.jihuahao.getText().toString();
                    if (mSoureList.get(position).getLrzt().equals("1")) {
                        EditorGuardianActivity.add_power = true;
                    } else {
                        EditorGuardianActivity.add_power = false;
                    }
                    intent = new Intent(getContext(), EditorGuardianActivity.class);
                    startActivity(intent);

                }
            });
            //补充风险点设置click事件
            mHolder.bcfxd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MyApplication.ShowWaitDialog(getContext());
                    Map<String, String> map = new HashMap<>();
                    map.put("jdjhbBh", mHolder.jihuahao.getText().toString());
                    map.put("lrdwId", MyApplication.getmLoginUser().getUserUnitId());
                    NetWorkApi.getBcfxd(map, new Callback<AddPointBean>() {
                                @Override
                                public void onResponse(Call<AddPointBean> call, Response<AddPointBean> response) {
                                    try {
                                        showAddDangerDailog(mHolder.jihuahao.getText().toString());
                                        AddPointBean mAddPointBean = response.body();
                                        mAddDangerPointDialog.AddDangerPoint(mAddPointBean);
                                        if (mSoureList.get(position).getLrzt().equals("1")) {
                                            mAddDangerPointDialog.showAdd();
                                        } else {
                                            mAddDangerPointDialog.hideAdd();
                                        }
                                    } catch (Exception e) {
                                        MyToast.showFail();
                                    }
                                    MyApplication.HideWaitDialog();
                                }

                                @Override
                                public void onFailure(Call<AddPointBean> call, Throwable t) {
                                    MyToast.showFail();
                                }
                            }
                    );
                }
            });

            return convertView;
        }

    }


    //显示补充风险点dialog
    void showAddDangerDailog(String position) {
        mAddDangerPointDialog = new AddDangerPointDialog(getContext());
        mAddDangerPointDialog.setCanceledOnTouchOutside(false);
        mAddDangerPointDialog.show();
        Window dialogwindow = mAddDangerPointDialog.getWindow();
        WindowManager.LayoutParams lp = dialogwindow.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        dialogwindow.setAttributes(lp);
        mAddDangerPointDialog.setJiHuaHao(position);
    }


    //点击每一条信息的计划号以后根据点击的计划号获取计划号数据并显示
    public void getCheckInfoData(String bh) {
        MyApplication.ShowWaitDialog(getContext());
        NetWorkApi.getCheckInfoData(bh, new Callback<CheckInfoBean>() {
                    @Override
                    public void onResponse(Call<CheckInfoBean> call, Response<CheckInfoBean> response) {
                        try {
                            CheckInfoBean mCheckInfoBean = response.body();
                            showCheckPlanDialog(mCheckInfoBean);
                        } catch (Exception e) {
                            MyToast.showFail();

                        }
                        MyApplication.HideWaitDialog();
                    }

                    @Override
                    public void onFailure(Call<CheckInfoBean> call, Throwable t) {
                        MyToast.showFail();

                    }
                }
        );
    }

    //显示计划详情diaog
    public void showCheckPlanDialog(CheckInfoBean mCheckInfoBean) {
        mZsrjhChaKanDialog = new ZsrjhChaKanDialog(getContext(), mCheckInfoBean);
        mZsrjhChaKanDialog.show();
    }


    //获取施工监护listview的数据 并更新
    //根据是否具有施工监护人员安排权限 获取数据
    public void LoadMoreDate() {
        pageNumber++;
        Map<String, String> map = new HashMap<>();
        map.put("pageNumber", String.valueOf(pageNumber));
        map.put("pageSize", String.valueOf(pageSize));
        map.put("loginDwxxApId", MyApplication.getmLoginUser().getUserUnitId());
        map.put("timeoutFlag", isTimeOut);
        map = setMap(map, mCheckSearchBean);
        MyApplication.ShowWaitDialog(getContext());
        NetWorkApi.getCheckListData(map, new Callback<CheckPlanBean>() {
                    @Override
                    public void onResponse(Call<CheckPlanBean> call, Response<CheckPlanBean> response) {
                        try {
                            MyApplication.HideWaitDialog();
                            mCheckPlanBean = response.body();

                            if (mCheckPlanBean.getMsg().equals("success") && mCheckPlanBean.getRows().size() == 0) {
//                                MyToast.showNoDate(getContext());
                            } else {
                                mSoureList.addAll(mCheckPlanBean.getRows());
                                mCheckListAdapter.notifyDataSetChanged();
                            }
                        } catch (Exception e) {
                            MyToast.showFail();

                        }
                        MyApplication.HideWaitDialog();
                        swipeRefreshLayout.finishLoadmore();
                    }

                    @Override
                    public void onFailure(Call<CheckPlanBean> call, Throwable t) {
                        MyToast.showFail();
                    }
                }

        );
    }

    public void RefreshAllDate(int PageNumber, int PageSize) {
        this.pageNumber = PageNumber;
        Map<String, String> map = new HashMap<>();
        map.put("pageNumber", String.valueOf(PageNumber));
        map.put("pageSize", String.valueOf(PageSize));
        map.put("loginDwxxCxId", MyApplication.getmLoginUser().getUserUnitId());
        map.put("timeoutFlag", isTimeOut);
        map = setMap(map, mCheckSearchBean);
        MyApplication.ShowWaitDialog(getContext());
        NetWorkApi.getCheckListData(map, new Callback<CheckPlanBean>() {
                    @Override
                    public void onResponse(Call<CheckPlanBean> call, Response<CheckPlanBean> response) {
                        try {
                            mCheckPlanBean = response.body();

                            if (mCheckPlanBean.getMsg().equals("success")) {
                                mSoureList = mCheckPlanBean.getRows();
                                mCheckListAdapter.notifyDataSetChanged();
                            }
                        } catch (Exception e) {
                            MyToast.showFail();

                        }
                        MyApplication.HideWaitDialog();
                        swipeRefreshLayout.finishRefresh();
                    }

                    @Override
                    public void onFailure(Call<CheckPlanBean> call, Throwable t) {
                        MyToast.showFail();
                    }
                }
//                new ObjectHttpResponseHandler(getActivity(), CheckPlanBean.class) {
//            @Override
//            public void Success(int i, org.apache.http.Header[] headers, Object object) {
//                try {
//                    mCheckPlanBean = (CheckPlanBean) object;
//                    if (mCheckPlanBean.getMsg() == null) {
//                        MyToast.showServerError(getContext());
//
//                        return;
//                    }
//                    if (mCheckPlanBean.getMsg().equals("success")) {
//                        mSoureList = mCheckPlanBean.getRows();
//                        mCheckListAdapter.notifyDataSetChanged();
//                    }
//                } catch (Exception e) {
//                    MyToast.showServerError(getContext());
//                }
//
//            }
//
//            @Override
//            public void Failure(int i, Header[] headers, String s, Throwable throwable) {
//                super.Failure(i, headers, s, throwable);
//                MyApplication.HideWaitDialog();
//                MyToast.showToast("更新失败");
//            }
//
//            @Override
//            public void onFinish() {
//                super.onFinish();
//                MyApplication.HideWaitDialog();
//                swipeRefreshLayout.finishRefresh();
//            }
//        }
        );


    }


    class ViewHolder {
        //施工计划
        TextView jihuahao;
        //施工日期
        TextView shigongriqi;
        //施工类别
        TextView shigongleixing;
        //施工地点
        TextView shigongdidian;
        //施工项目
        TextView shigongxiangmu;
        //施工项目
        TextView jianhurenyuan;

        //编辑监护人按钮
        TextView bjjhr;
        //补充风险点按钮
        TextView bcfxd;


        LinearLayout editlayout;
        LinearLayout linearlayout;

    }

    public Map<String, String> setMap(Map<String, String> map, CheckSearchBean Bean) {
        if (Bean != null) {
            if (Bean.getSgrq() != null && !Bean.getSgrq().equals("")) {
                map.put("searchDate", Bean.getSgrq());
            } else {
                map.put("searchDate", DateUtil.getCurDate());
            }
            if (Bean.getJcr() != null && !Bean.getJcr().equals("")) {
                map.put("seachJcrName", Bean.getJcr());
            }
            if (Bean.getXm() != null && !Bean.getXm().equals("")) {
                map.put("searchXlMc", Bean.getXm());
            }
            if (Bean.getDwhbm() != null) {
                map.put("searchDwId", Bean.getDwhbm().getLjyyxDwxxId());
            }
            if (Bean.getRjhh() != null) {
                map.put("searchBh", Bean.getRjhh());
            }
        }
        return map;
    }

}
